#include "stdafx.h"
/*

@returns error code
*/
int get_poly(std::vector<graph::lat_lon_t> point_list, std::string path_type, std::list<graph::lat_lon_t>& result)
{
    using namespace graph;
    using namespace graph::algorithm;
    //Getting nearest vertices to start and finish
    global_data_t& global = global::get_instance(); //get reference to global data
    point_t start_p(point_list[0], point_list[1]);
    point_t finish_p(point_list[2], point_list[3]);
    
    std::cout << "Processing request:        " << std::endl
              << "   s_lat: " << start_p.lat_  << std::endl 
              << "   s_lon: " << start_p.lon_  << std::endl
              << "   f_lat: " << finish_p.lat_ << std::endl 
              << "   f_lng: " << finish_p.lon_ << std::endl 
              << "   p_type: " << path_type    << std::endl;

    global.set_new_view(path_type);
    
    astar_initializer_t astar_initializer(*global.current_view_, start_p, finish_p);
    if (astar_initializer.get_last_error())
      return astar_initializer.get_last_error();    
    
    astar_search_t<release, bidirectional> as(global.current_view_, astar_initializer);
    
    if (astar_initializer.get_last_error())
      return astar_initializer.get_last_error();
    
    as.run(true, 0);
    //Come back and take the shortest path    
    if (as.is_all_ended())
    {   
        as.fill_shpath(result);
        return 0;
    }   
    else
    {
        return PATH_NOT_FOUND_ERROR;
    }
}

int handle_request(fcgi::request& req)
{
   req.load(fcgi::parse_all);
   fcgi::response resp;
   resp << fcgi::content_type("text/plain");      
   
   std::vector<graph::lat_lon_t> user_points;
   user_points.push_back( boost::lexical_cast<graph::lat_lon_t>(req.get["lat1"]) );
   user_points.push_back( boost::lexical_cast<graph::lat_lon_t>(req.get["lng1"]) );
   user_points.push_back( boost::lexical_cast<graph::lat_lon_t>(req.get["lat2"]) );
   user_points.push_back( boost::lexical_cast<graph::lat_lon_t>(req.get["lng2"]) );   
   std::string path_type;
   path_type = req.get["path-type"];
   std::list<graph::lat_lon_t> sh_path;
   int status = get_poly(user_points, path_type, sh_path);
   if (!status)
   {
       std::cout << "successfully processed" << std::endl;
       // making json [lat1, lng1, .., lati, lngi, ..]
       resp << "["; 
       std::list<graph::lat_lon_t>::iterator it = sh_path.begin();
       resp << boost::lexical_cast<std::string>(*it);
       ++it;
       for(; it != sh_path.end(); ++it)
       {
          resp << ",";
          resp << boost::lexical_cast<std::string>(*it);
       }
       resp << "]";
   }
   else
   {
      std::cout << "error " << status << std::endl;
      resp << "\"err_code_";
      resp << boost::lexical_cast<std::string>(status);
      resp << "\"";
   }
   //resp << "Response content-length == " << resp.content_length();
   return fcgi::commit(req, resp);
}

